#include "led.h"
#include "FreeRTOS.h"
#include "task.h"
#include "./lcd/bsp_ili9341_lcd.h"
#include "usart.h"
#include "key.h"
#include "queue.h"
#include "semphr.h"
#include "stdio.h"

static TaskHandle_t appTaskCreateHandle = NULL;
static TaskHandle_t takeTaskCreateHandle = NULL;
static TaskHandle_t giveTaskCreateHandle = NULL;

SemaphoreHandle_t countSem_handle = NULL;

static void App_Task(void);
static void Take_Task(void* pvParameters);
static void Give_Task(void* pvParameters);

int main(void)
{ 
	BaseType_t xReturn = pdPASS;
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);//设置系统中断优先级分组4
	KEY_Init();
	LED_Init();		        //初始化LED端口
	ILI9341_Init();//液晶初始化    
	LCD_SetColors(BLACK,WHITE);//设置白底黑字
	LCD_SetFont(&Font8x16);//设置字体大小
	ILI9341_Clear(0,0,LCD_X_LENGTH,LCD_Y_LENGTH);//清屏
  ILI9341_GramScan ( 6 );//设置显示模式
	USART_Config(115200);
  LED_Color(LED_OFF);
	
	xReturn = xTaskCreate(
		App_Task,
	  "APP_Task",
		512,
		NULL,
		1,
	  &appTaskCreateHandle
	);
	if(pdPASS == xReturn){
		vTaskStartScheduler();          //开启任务调度
	}
  else{
		printf("Error Start RTOS\n");
	}
	
}

static void App_Task(void)
{
	BaseType_t xReturn = pdPASS;
	taskENTER_CRITICAL(); //进入临界区
	countSem_handle = xSemaphoreCreateCounting(5,5);
	if(countSem_handle!=NULL)
	{
		printf("Success Create CountSem_handle\n");
	}
	
	xReturn = xTaskCreate(
		Take_Task,
	  "Take_Task",
		512,
		NULL,
		4,
	  &takeTaskCreateHandle
	);
	if(pdPASS == xReturn){
		printf("Success Create TakeTask\n");
	}
	
	xReturn = xTaskCreate(
		Give_Task,
	  "Give_Task",
		512,
		NULL,
		3,
	  &giveTaskCreateHandle
	);
	if(pdPASS == xReturn){
		printf("Success Create GiveTask\n");
	}
	
	vTaskDelete(appTaskCreateHandle);
	taskEXIT_CRITICAL();//退出临界区
}

static void Take_Task(void* pvParameters)
{
	BaseType_t xReturn = pdTRUE;
	while(1){
		if(GET_KEY1)
		{
				xReturn = xSemaphoreTake(countSem_handle,0);
				if(xReturn == pdTRUE)
				{
					printf("Success get a park\n");
				}
				else
				{
					printf("Sorry we don't hava park now\n");
				}
		}
		vTaskDelay(20);
	}
}

static void Give_Task(void* pvParameters)
{
		BaseType_t xReturn = pdTRUE;
		while(1){
			if(GET_KEY2)
			{
				xReturn = xSemaphoreGive(countSem_handle);
				if(xReturn == pdTRUE)
				{
					printf("Success free a park\n");
				}
				else
				{
					printf("Sorry we don't have park to free now\n");
				}
			}
			vTaskDelay(20);
		}
}

